<template>
  <div class="app-container">
    <!-- 添加或修改单排信息 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="题库" prop="questionBankName">
            <el-select v-model="form.questionBankName" value-key="questionBankId" placeholder="请选择题库" :disabled="this.form.planId === undefined ? false:true" filterable size="small"
                       style="width: 100%;" @change="function(q) {return bindData(q)}">
              <el-option
                      v-for="(q,index) in questionBankListOptions"
                      :key="q.questionBankId"
                      :label="q.questionBankName"
                      :value="q"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目代码" prop="projectCode">
            <el-input v-model="form.projectCode" size="small" width :disabled="true"  />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" size="small" :disabled="true"  />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="剩余报考人数" prop="signUpNumber">
            <el-input-number v-model="signUpNumber" placeholder="报考人数" size="small" controls-position="right" style="width: 100%;" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="考场" prop="examRoomDTO">
            <el-select v-model="form.examRoomDTO" value-key="examRoomId" filterable placeholder="请选择考场" size="small" style="width: 100%;"
                       :disabled="(postponeStatus === true || cancelStatus === true)" @change="function(q) {return bindRoomData(q)}">
              <el-option
                      v-for="dict in examRoomList"
                      :key="dict.examRoomId"
                      :label="dict.examRoomName"
                      :value="dict"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="剩余座位" prop="seatCount">
            <el-input-number v-model="form.examRoomDTO === undefined ? seatCount : form.examRoomDTO.seatCount"
                      placeholder="剩余座位" size="small" :disabled="true" controls-position="right" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="排考人数" prop="examNumber">
            <el-input-number v-model="form.examNumber" size="small" controls-position="right"  :min="0" :max="100"
                             :disabled="this.form.planId === undefined ? false:true" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="监考老师" prop="invigilatorName">
            <el-select v-model="form.invigilatorName" value-key="employeeId" placeholder="支持工号/姓名搜索" filterable remote clearable
                       :disabled="(postponeStatus === true || cancelStatus === true)" size="small" style="width: 100%;"
                       :remote-method="getEmployee">
              <el-option
                      v-for="(q,index) in employeeListOptions"
                      :key="q.employeeId"
                      :label="q.employeeName+'-'+q.employeeId"
                      :value="q.employeeName+'-'+q.employeeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="阅卷老师" prop="examinersName">
            <el-select v-model="form.examinersName" value-key="employeeId" placeholder="支持工号/姓名搜索" filterable remote clearable
                       :disabled="(postponeStatus === true || cancelStatus === true)" size="small" style="width: 100%;"
                       :remote-method="getEmployee" >
              <el-option
                      v-for="(q,index) in employeeListOptions"
                      :key="q.employeeId"
                      :label="q.employeeName+'-'+q.employeeId"
                      :value="q.employeeName+'-'+q.employeeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="试卷类型" prop="paperType">
            <el-select v-model="form.paperType"  placeholder="请选择试卷类型" size="small" @change="paperOptions"
                       :disabled="(postponeStatus === true || cancelStatus === true)" style="width: 100%;" >
              <el-option
                      v-for="dict in paperTypeList"
                      :key="dict.code"
                      :label="dict.name"
                      :value="dict.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="选择试卷" prop="paperId">
            <el-select v-model="form.paperId" value-key="paperId" clearable placeholder="请选择试卷" filterable size="small" style="width: 100%;"
                       :disabled="(form.paperType === '1' ? false : true) || (postponeStatus === true || cancelStatus === true)">
              <el-option
                      v-for="(q,index) in paperListOptions"
                      :key="q.paperId"
                      :label="q.paperName"
                      :value="q.paperId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="考试方式" prop="examWay">
            <el-select v-model="form.examWay" value-key="code" placeholder="请选择考试方式" size="small"
                       :disabled="this.form.planId === undefined ? false:true" style="width: 100%;" >
              <el-option
                      v-for="(q,index) in getExamWayOptions"
                      :key="q.code"
                      :label="q.name"
                      :value="q.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="考试日期" prop="examDate">
            <el-date-picker type="date"  size="small" :picker-options="pickerOptions" v-model="form.examDate" :clearable="false" :disabled="(postponeStatus === true || cancelStatus === true)"
                            value-format="yyyy-MM-dd" placeholder="请选择考试日期" @change="getRoomCacheSeatCount" style="width: 100%;"  />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="考试时间" prop="examTime" >
            <el-time-select size="small"  placeholder="开始时间" :editable="false" :clearable="false" :disabled="(postponeStatus === true || cancelStatus === true)"
                            v-model="form.examStart" @change="getRoomCacheSeatCount" style="width: 30%;"
                            :picker-options="{
                    start: '07:00',
                    step: '00:30',
                    end: '21:00',
                    maxTime: form.examEnd
                  }">
            </el-time-select>
            <span style="padding: 0px 5px 0px 5px;">至</span>
            <el-time-select size="small"  placeholder="结束时间" :editable="false" :clearable="false" :disabled="(postponeStatus === true || cancelStatus === true)"
                            v-model="form.examEnd" @change="getRoomCacheSeatCount" style="width: 30%;"
                            :picker-options="{
                      start: '07:00',
                      step: '00:30',
                      end: '21:00',
                      minTime: form.examStart
                    }">
            </el-time-select>
          </el-form-item>
        </el-col>
        <!--<el-col :span="8">
          <el-form-item label="结束时间" prop="examEnd">
            <el-time-select size="small"  placeholder="结束时间" :editable="false" :clearable="false" :disabled="(postponeStatus === true || cancelStatus === true)"
                            v-model="form.examEnd" @change="getRoomCacheSeatCount" style="width: 100%;"
                            :picker-options="{
                      start: '07:00',
                      step: '00:30',
                      end: '21:00',
                      minTime: form.examStart
                    }">
            </el-time-select>
          </el-form-item>
        </el-col>-->
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="考试须知" prop="examNotice" >
            <el-input type="textarea" placeholder="请输入内容" v-model="form.examNotice" :disabled="(postponeStatus === true || cancelStatus === true)"
                      :autosize="{ minRows: 2, maxRows: 4}"/>
          </el-form-item>
        </el-col>
      </el-row>
<!--    延期原因  -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="延期原因" prop="postponeCause" v-if="postponeStatus" >
            <el-input type="textarea" placeholder="请输入延期考试原因"  v-model="form.postponeCause"
                      :autosize="{ minRows: 2, maxRows: 4}"/>
          </el-form-item>
        </el-col>
      </el-row>
<!--    延期日期  -->
      <el-row>
        <el-col :span="8">
          <el-form-item label="延期日期" prop="postponeDate" v-if="postponeStatus">
            <el-date-picker type="date"  size="small" :picker-options="pickerOptions" v-model="form.postponeDate" :clearable="false"
                            value-format="yyyy-MM-dd" placeholder="请选择延期日期" style="width: 100%;"  />
          </el-form-item>
        </el-col>
      </el-row>
<!--    取消原因  -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="取消原因" prop="cancelCause" v-if="cancelStatus" >
            <el-input type="textarea" placeholder="请输入取消考试原因"  v-model="form.cancelCause" @blur="bindDate"
                      :autosize="{ minRows: 2, maxRows: 4}"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer" style="float:right">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm('submit')" size="small">保 存</el-button>
      <el-button @click="cancel"  size="small">取 消</el-button>
    </div>
  </div>
</template>

<script>
  import {listQuestionBank} from "@/api/question/questionBank";
  import {getExamPlanList,getExamPlanById,addExamPlan,updateExamPlan,postponeExamPlan,cancelExamPlan} from "@/api/exam/examPlan"
  import {getSignUpListByQuestionBankId} from "@/api/exam/signUp";
  import {getPaperListByQuestionBankId} from "@/api/question/paper";
  import {getCacheSeatCount} from "@/api/exam/examRoom";
  // 查询人员
  import {searchByPage} from "@/api/employee/employee";
  export default {
    name: "singlePlanForm",
    props: {
      // 题库表单信息
      form: Object,
      // 考试方式
      getExamWayOptions: Array,
      // 考场
      examRoomList: Array,
      // 延期
      postponeStatus: Boolean,
      // 取消
      cancelStatus: Boolean,
    },
    data() {
      // 自定义校验考试时间
      var checkExamTime = (rule, value, callback) => {
        const examStart = this.form.examStart;
        const examEnd = this.form.examEnd;
        if (!examStart || !examEnd) {
          return callback(new Error('考试时间不能为空！'));
        } else {
          callback();
        }
      };
      // 自定义校验试卷选择
      var checkPaperId = (rule, value, callback) => {
        const paperType = this.form.paperType;
        if ('1' === paperType && !value) {
          return callback(new Error('请选择试卷！'));
        } else {
          callback();
        }
      };
      return {
        // 禁用当前日期前日期
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
        // 按钮loading
        buttonLoading: false,
        // 表单校验
        rules: {
          projectCode: [
            {required: true, message: "项目代码不能为空", trigger: "blur"}
          ],
          projectName: [
            {required: true, message: "项目名称不能为空", trigger: "blur"}
          ],
          questionBankName: [
            {required: true, message: "请选择题库", trigger: "blur"}
          ],
          examDate: [
            {required: true, message: "请选择考试日期", trigger: "blur"}
          ],
          examTime: [
            {required: true, validator: checkExamTime, trigger: "blur"}
          ],
          /*examStart: [
            {required: true, message: "请选择考试开始时间", trigger: "blur"}
          ],
          examEnd: [
            {required: true, message: "请选择考试结束时间", trigger: "blur"}
          ],*/
          examNumber: [
            {required: true, message: "排考人数不能为空", trigger: "blur"}
          ],
          invigilatorName: [
            {required: true, message: "请选择监考老师", trigger: "blur"}
          ],
          examRoomDTO: [
            {required: true, message: "请选择考场", trigger: "blur"}
          ],
          paperType: [
            {required: true, message: "请选择试卷类型", trigger: "blur"}
          ],
          paperId: [
            {required: true, validator: checkPaperId, trigger: "blur"}
          ],
          examWay: [
            {required: true, message: "请选择考试方式", trigger: "blur"}
          ],
          examNotice: [
            {required: true, message: "考试须知不能为空", trigger: "blur"}
          ],
          postponeCause: [
            {required: true, message: "延期考试原因不能为空", trigger: "blur"}
          ],
          postponeDate: [
            {required: true, message: "延期日期不能为空", trigger: "blur"}
          ],
          cancelCause: [
            {required: true, message: "取消考试原因不能为空", trigger: "blur"}
          ],

        },
        //题库信息下拉框
        questionBankListOptions: [],
        // 试卷类型数据字典
        paperTypeList: [],
        // 试卷列表下拉框
        paperListOptions: [],
        // 人员信息
        employeeListOptions: [],
        // 考场座位数
        seatCount: 0,
        //剩余报考人数
        signUpNumber: undefined,
      }
    },
    created() {
      //题库信息
      listQuestionBank({
        'pageParameter': {page: 1, rows: 1000},
        'searchParams': {}
      }).then(response => {
        this.questionBankListOptions = response.responseBody.result;
      })

      //查询试卷类型字典状态
      this.getDicts("paper_type").then(response => {
        this.paperTypeList = response.responseBody.result;
      });
    //  初始化人员
      this.getEmployee();

    //  初始化剩余报考人数和题库所属试卷(编辑时触发使用)
      if (this.form.planId !== undefined) {
        this.getSignUpList(this.form.questionBankId);
        // 题库所属试卷
        this.getPaperList(this.form.questionBankId)
      }

    //  初始化默认第一个考试（新增考试计划触发使用）
      if (this.form.examRoomDTO === undefined) {
        this.form.examRoomDTO = this.examRoomList[0];
        this.bindRoomData(this.examRoomList[0]);
      }
    },
    methods: {
      //选择题库触发绑定相关数据
      bindData(q) {
        this.form.questionBankName = q.questionBankName;
        this.form.questionBankId = q.questionBankId;
        this.form.projectCode = q.projectCode;
        this.form.projectName = q.projectName;
        // 题库所属剩余报考人数
        this.getSignUpList(q.questionBankId);
        // 题库所属试卷
        this.getPaperList(q.questionBankId)
      },
      // 通过题库Id获取报考人员列表（除取消考试和已排考人员外）
      getSignUpList(questionBankId) {
        getSignUpListByQuestionBankId(questionBankId).then(res => {
          this.signUpNumber = res.responseBody.length; //剩余报考人数
        }).catch(err => {
          console.log(err);
        })
      },
      // 选择考场绑定相关数据
      bindRoomData(q) {
        this.form.examRoomId = q.examRoomId;
        // 解决下拉框赋予初始值后页面不重新渲染
        this.$forceUpdate()
      //  获取缓存剩余数：
        this.getRoomCacheSeatCount();
      },
      // 获取缓存的剩余座位数
      getRoomCacheSeatCount() {
        //查询缓存参数
        const queryRoomCachePrams = {
          examRoomId: this.form.examRoomId,
          examDate: this.form.examDate,
          examStart: this.form.examStart,
          examEnd: this.form.examEnd
        };
        // 所有参数都具备才可请求
        if (
                queryRoomCachePrams.examRoomId !== undefined &&
                queryRoomCachePrams.examDate !== undefined &&
                queryRoomCachePrams.examStart !== undefined &&
                queryRoomCachePrams.examEnd !== undefined
        ) {
          getCacheSeatCount(queryRoomCachePrams).then(res => {
            // 剩余座位数
            this.form.examRoomDTO.seatCount = res.responseBody;
          });
        }
      },
      //绑定取消日期
      bindDate() {
        let year = new Date().getFullYear();
        let month = new Date().getMonth() + 1;
        let day = new Date().getDate();
        this.form.cancelDate = year + "-" + month + "-" + day;
      },

      // 通过题库Id获取所属试卷（手动组卷）
      getPaperList(questionBankId) {
        getPaperListByQuestionBankId(questionBankId).then(res => {
            this.paperListOptions = res.responseBody;
        }).catch(err => {
          console.log(err);
        })
      },
      // 通过工号或姓名搜索人员
      getEmployee(employeeId) {
        // console.log("选中的工号或姓名：",employeeId);
        searchByPage({
          'pageParameter': {page: 1, rows: 50},
          'searchParams': {employeeId:employeeId,employeeName:employeeId},
          'keyWord': 'true'
        }).then(res => {
          this.employeeListOptions = res.responseBody.result;
        })
      },
      // 试卷类型触发选择试卷
      paperOptions(item) {
        // console.log("=======",item);
        if (item === '0') { // 智能组卷清空已选择的试卷
          delete this.form.paperId;
        }
      },
      /** 提交按钮 */
      submitForm(flag) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            // 延期考试计划
            if (this.postponeStatus) {
              //0:正常（默认），1：延期，2：取消
              this.form.planStatus = '1';
              postponeExamPlan(this.form).then(response => {
                if (response.retCode === '200') {
                  if (response.responseBody !== 0) {
                    this.msgSuccess(response.message);
                    // 关闭对话框
                    this.$emit("cancelDialog");
                    //刷新数据
                    this.$emit("submitForm");
                  } else {
                    this.msgWarning(response.message);
                  }
                }
                // this.msgSuccess("修改成功");
              }).finally(() => {
                this.buttonLoading = false;
              });
              return;
            }
            // 取消考试计划
            if (this.cancelStatus) {
              //0:正常（默认），1：延期，2：取消
              this.form.planStatus = '2';
              cancelExamPlan(this.form).then(response => {
                if (response.retCode === '200') {
                  if (response.responseBody !== 0) {
                    this.msgSuccess(response.message);
                    // 关闭对话框
                    this.$emit("cancelDialog");
                    //刷新数据
                    this.$emit("submitForm");
                  } else {
                    this.msgWarning(response.message);
                  }
                }
                // this.msgSuccess("修改成功");
              }).finally(() => {
                this.buttonLoading = false;
              });
              return;
            }

            if (this.form.examNumber === 0) {
              this.msgWarning("考试人数不能为0人！");
              // console.log("===提交表单信息==", JSON.parse(JSON.stringify(this.form)));
              this.buttonLoading = false;
              return;
            }
            if (this.form.examNumber > this.form.examRoomDTO.seatCount) {
              this.msgWarning("考试人数不能大于考场座位数！");
              // console.log("===提交表单信息==", JSON.parse(JSON.stringify(this.form)));
              this.buttonLoading = false;
              return;
            }
            if (this.form.planId !== undefined) { // 修改考试计划
              //0:正常，1：延期，2：取消
              this.form.planStatus = '0';
              updateExamPlan(this.form).then(response => {
                if (response.retCode === '200') {
                  if (response.responseBody !== 0) {
                    this.msgSuccess(response.message);
                    // 关闭对话框
                    this.$emit("cancelDialog");
                    //刷新数据
                    this.$emit("submitForm");
                  } else {
                    this.msgWarning(response.message);
                  }
                }
                // this.msgSuccess("修改成功");
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else { // 新增考试计划
              addExamPlan(this.form).then(response => {
                if (response.retCode === '200') {
                  if (response.responseBody !== 0) {
                    this.msgSuccess(response.message);
                    // 关闭对话框
                    this.$emit("cancelDialog");
                    //刷新数据
                    this.$emit("submitForm");
                  } else {
                    this.msgWarning(response.message);
                  }
                }
                // this.msgSuccess("新增成功");
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },

      // 取消按钮
      cancel() {
        // 清空
        this.$emit("cancelDialog");
      },
    }

  }

</script>

<style scoped>

</style>
